package user_profile

import (
	"context"
	"encoding/xml"
	"fmt"
	"os"
	"regexp"
	"strings"
	"time"
	"unicode/utf8"

	"algo-sdk-go/project/matchmaking/matchMaking-api/internal/svc"
	"algo-sdk-go/project/matchmaking/matchMaking-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type Json2XmlLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewJson2XmlLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Json2XmlLogic {
	return &Json2XmlLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *Json2XmlLogic) Json2Xml(req *types.Json2XmlRequest) (resp *types.Json2XmlResponse, err error) {

	handlerFunc(req)

	return
}

type CDATA string

func (c CDATA) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	start.Attr = []xml.Attr{
		{Name: xml.Name{Local: "xmlns"}, Value: ""},
	}
	return e.EncodeElement(struct {
		string `xml:",cdata"`
	}{string(c)}, start)
}

type Product struct {
	XMLName                  xml.Name `xml:"product"`
	ProductID                string   `xml:"product_id"`
	ProductName              string   `xml:"product_name"`
	ImageURL                 string   `xml:"image_url"`
	TargetURLMiniProgramID   string   `xml:"target_url_mini_program_id"`
	TargetURLMiniProgramPath string   `xml:"target_url_mini_program_path"`
	FirstCategoryName        string   `xml:"first_category_name"`
	SecondCategoryName       string   `xml:"second_category_name"`
	ThirdCategoryName        string   `xml:"third_category_name"`
	ProductSaleStatus        string   `xml:"product_sale_status"`
	ExpirationTime           string   `xml:"expiration_time"`
	StockVolume              string   `xml:"stock_volume"`
	CreatedTime              string   `xml:"created_time"`
	LastmodTime              string   `xml:"lastmod_time"`
	CustomData               string   `xml:"custom_data"`
	BrandName                string   `xml:"brand_name"`
}

type ProductSet struct {
	XMLName  xml.Name  `xml:"product_set"`
	Products []Product `xml:"product"`
}

func handlerFunc(input *types.Json2XmlRequest) {
	products := ProductSet{}
	currentTime := time.Now().Format("2006-01-02 15:04:05")
	//splitSymbol := []string{"（", "）", "【", "「", "(", "[", "{", "}", "+", "*", "&", "%", "$", "#", "@", "!", "`", "~"}

	reMl := regexp.MustCompile(`\s*\d+ml(?:\*\d+)?`)           // 匹配 " 數字ml" 或 "數字ml" 或 " 數字ml*數字" 或 "數字ml*數字"
	reSymbolNumber := regexp.MustCompile(`[\\u4e00-\\u9fa5]+`) // 匹配所有非中英文字符
	reSymbolAlpha := regexp.MustCompile(`[a-zA-Z]+`)           // 匹配所有非中英文字符

	reBracketsAll := regexp.MustCompile(`\s*[【】「」{}()\[\]（）].*?[【】「」{}()\[\]（）]\s*`)

	for _, goods := range input.Data.GoodsList {
		product := Product{
			ProductID:              goods.ID,
			ImageURL:               "",
			TargetURLMiniProgramID: "wxd103d6c037236ee0",
			TargetURLMiniProgramPath: fmt.Sprintf("/pages/main/product/subject/detail/index?goodsId=%s&source_from=market-yz-tencent-%s-%d",
				goods.ID, goods.BrandEn, goods.LefoxID),
			ProductSaleStatus: "PRODUCT_SALE_STATUS_ONLINE",
			ExpirationTime:    "2035-01-01 00:00:00",
			StockVolume:       "999",
			CreatedTime:       currentTime,
			LastmodTime:       currentTime,
			CustomData:        fmt.Sprintf("品牌:%s;规格:正常规格;", goods.Brand),
			BrandName:         goods.Brand,
		}
		/*
			productName := goods.AppendTitle
			for _, r := range splitSymbol {
				flag := strings.Split(productName, r)
				if len(flag) > 1 {
					productName = flag[0]
				}
			}*/

		if goods.CombinationGoods != nil {
			product.ProductName = fmt.Sprintf("%s套装", goods.Brand)
		} else {
			productName := goods.AppendTitle
			productName = reMl.ReplaceAllString(productName, "")           // 移除 "數字ml" 和 "數字ml*數字"
			productName = reSymbolAlpha.ReplaceAllString(productName, "")  // 移除所有非中英文字符
			productName = reSymbolNumber.ReplaceAllString(productName, "") // 移除所有非中英文字符
			productName = reBracketsAll.ReplaceAllString(productName, "")

			replacements := []string{" ", "-", "/", "\\", "【", "「", "」", "】", ",", ".", "(", ")", "[", "]", "{", "}", "+", "*", "&", "%", "$", "#", "@", "!", "`", "~"}
			for _, r := range replacements {
				productName = strings.ReplaceAll(productName, r, "")
			}
			product.ProductName = productName
		}

		if utf8.RuneCountInString(product.ProductName) < 7 {
			product.ProductName = product.ProductName + "常规版"
		}

		if strings.Contains(goods.AppendTitle, "五粮液") || strings.Contains(goods.AppendTitle, "52度") {
			product.ProductName = "五粮液52度常规版"
		}

		/*productName := goods.AppendTitle
		replacements := []string{" ", "-", "/", "\\", ",", ".", "(", ")", "[", "]", "{", "}", "+", "*", "&", "%", "$", "#", "@", "!", "`", "~"}
		for _, r := range replacements {
			productName = strings.ReplaceAll(productName, r, "")
		}
		product.ProductName = productName*/

		if len(goods.MainImg) > 0 {
			product.ImageURL = goods.MainImg[0]
		}

		categories := strings.Split(goods.Category, "-")
		if len(categories) > 1 {
			product.FirstCategoryName = categories[1]
		}
		if len(categories) > 2 {
			product.SecondCategoryName = categories[2]
		}
		if len(categories) > 3 {
			product.ThirdCategoryName = categories[3]
		}

		// Wrap string values in CDATA
		product.ProductID = fmt.Sprintf("<![CDATA[%s]]>", product.ProductID)
		product.ProductName = fmt.Sprintf("<![CDATA[%s]]>", product.ProductName)
		product.ImageURL = fmt.Sprintf("<![CDATA[%s]]>", product.ImageURL)
		product.TargetURLMiniProgramID = fmt.Sprintf("<![CDATA[%s]]>", product.TargetURLMiniProgramID)
		product.TargetURLMiniProgramPath = fmt.Sprintf("<![CDATA[%s]]>", product.TargetURLMiniProgramPath)
		product.FirstCategoryName = fmt.Sprintf("<![CDATA[%s]]>", product.FirstCategoryName)
		product.SecondCategoryName = fmt.Sprintf("<![CDATA[%s]]>", product.SecondCategoryName)
		product.ThirdCategoryName = fmt.Sprintf("<![CDATA[%s]]>", product.ThirdCategoryName)
		product.ProductSaleStatus = fmt.Sprintf("<![CDATA[%s]]>", product.ProductSaleStatus)
		product.ExpirationTime = fmt.Sprintf("<![CDATA[%s]]>", product.ExpirationTime)
		product.StockVolume = fmt.Sprintf("<![CDATA[%s]]>", product.StockVolume)
		product.CreatedTime = fmt.Sprintf("<![CDATA[%s]]>", product.CreatedTime)
		product.LastmodTime = fmt.Sprintf("<![CDATA[%s]]>", product.LastmodTime)
		product.CustomData = fmt.Sprintf("<![CDATA[%s]]>", product.CustomData)
		product.BrandName = fmt.Sprintf("<![CDATA[%s]]>", product.BrandName)

		products.Products = append(products.Products, product)
	}

	output, err := xml.MarshalIndent(products, "", "  ")
	if err != nil {
		fmt.Println("Error marshalling XML:", err)
		return
	}

	// Add the XML header
	//xmlOutput := xml.Header + "<product_set>\n" + string(output) + "</product_set>\n"
	xmlOutput := string(output)

	fmt.Println(xmlOutput)

	// You can also write the output to a file if needed
	err = os.WriteFile("output.xml", []byte(xmlOutput), 0644)
	if err != nil {
		fmt.Println("Error writing to file:", err)
		return
	}
}
